﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using LearnMAUI2.Models;
using LearnMAUI2.Services;

namespace LearnMAUI2.ViewModels;

public class TodayPageViewModel : ObservableObject
{
    private readonly ITodayPoetryService _todayPoetryService;

    private readonly IContentNavigationService _contentNavigationService;
    private readonly ITodayImageService _todayImageService;

    //页面完全加载后加载数据
    private readonly Lazy<RelayCommand> _lazyLoadCommand;
    //显示完全内容
    private readonly Lazy<AsyncRelayCommand> _lazyShowDetailCommand;


    private bool _isLoading;

    private TodayPoetry? _todayPoetry;

    //图片
    private TodayImage _todayImage;

    public TodayPageViewModel(ITodayPoetryService todayPoetryService, IContentNavigationService contentNavigationService, ITodayImageService todayImageService)
    {
        _todayPoetryService = todayPoetryService;
        _contentNavigationService = contentNavigationService;

        _lazyLoadCommand = new Lazy<RelayCommand>(() => new RelayCommand(LoadedCommandFunction));
        _lazyShowDetailCommand = new Lazy<AsyncRelayCommand>(() => new AsyncRelayCommand(ShowDetailCommandFunction));
        _todayImageService = todayImageService;
    }
    public RelayCommand LoadedCommand => _lazyLoadCommand.Value;

    public AsyncRelayCommand ShowDetailCommand => _lazyShowDetailCommand.Value;

    public void LoadedCommandFunction()
    {
        Task.Run(async () =>
        {
            IsLoading = true;
            TodayPoetry = await _todayPoetryService.GetTodayPoetryAsync();
            await Task.Delay(5000);//延迟5s，可以看到Loading...，但此时不会阻塞界面，点击其他界面是正常的
            IsLoading = false;
        });

        Task.Run(async () => 
        {
            //显示图片
            TodayImage = await _todayImageService.GetTodayImageAsync();

            var checkUpdate = await _todayImageService.CheckUpdateAsync();
            if (checkUpdate.HasUpdate)
            {
                TodayImage = checkUpdate.TodayImage;
            }
        });   
    }
    //导航到详细页面
    public async Task ShowDetailCommandFunction()
    {
        await _contentNavigationService.NavigateToAsync(ContentNavigationConstant.TodayDetailPage);
    }
    public bool IsLoading
    {
        get => _isLoading;
        set => SetProperty(ref _isLoading, value);
    }
    public TodayPoetry? TodayPoetry
    {
        get => _todayPoetry;
        set => SetProperty(ref _todayPoetry, value);
    }
    public TodayImage TodayImage
    {
        get => _todayImage;
        set => SetProperty(ref _todayImage, value);
    }
}
